/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.google.code.netbuilder.xmlaccess;

import com.google.code.netbuilder.dal.entities.Equipment;
import com.google.code.netbuilder.dal.entities.ManagedObject;
import java.io.*;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 *
 * @author Андрей
 */
public class XmlAccessor
{
    private JAXBContext jaxbContext;
    private Marshaller marshaller;
    private Unmarshaller unmarshaller;
    private XmlEntitiesWrapper wrapper;
    
    private static XmlAccessor singletonInstance = null;
    
    public static XmlAccessor getInstance() throws JAXBException
    {
        if(singletonInstance == null)
        {
            singletonInstance = new XmlAccessor();
        }
        
        return singletonInstance;
    }
    
    private XmlAccessor() throws JAXBException
    {
        jaxbContext = JAXBContext.newInstance(XmlEntitiesWrapper.class);
        
        marshaller = jaxbContext.createMarshaller();
        unmarshaller = jaxbContext.createUnmarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        wrapper = new XmlEntitiesWrapper();
    }
    
    
    
    public void marshal(List<? extends ManagedObject> inList, 
                         String filePath) throws JAXBException
    {
        wrapper.setWrapped(inList);
        File outputFile = new File(filePath);
        marshaller.marshal(wrapper, outputFile);
    }
    
    public List<? extends ManagedObject> unmarshal(String filePath) throws JAXBException
    {
        wrapper = new XmlEntitiesWrapper();
        File inputFile = new File(filePath);
        wrapper = (XmlEntitiesWrapper)unmarshaller.unmarshal(inputFile);
        return wrapper.getWrapped();
    }
    
    public String marshalToString(List<? extends ManagedObject> inList) throws JAXBException
    {
        wrapper.setWrapped(inList);
        Writer stringWriter = new StringWriter();
        marshaller.marshal(wrapper, stringWriter);
        return stringWriter.toString();
    }
    
    public List<? extends ManagedObject> unmarshalFromString(String destString) throws JAXBException
    {
        wrapper = new XmlEntitiesWrapper();
        Reader stringReader = new StringReader(destString);
        wrapper = (XmlEntitiesWrapper)unmarshaller.unmarshal(stringReader);
        return wrapper.getWrapped();
    } 
    
}
